/* =========================================================
**********************Fix css for IE************************
========================================================== */
jQuery(document).ready(function(){
	jQuery("#main-menu li:last-child").css("border-bottom",'none');
	jQuery(".social-links li:last-child").css("margin-right",0);
	jQuery(".pagination li:last-child").css("margin-right",0);
});
/* =========================================================
Left Panel
============================================================ */
jQuery(document).ready(function(){
	jQuery("#left-panel").click(function() {
		jQuery(this).toggleClass("close-panel");
		jQuery("#sidebar").toggle(300);
	});

})
/* =========================================================
*************************Sub Menu***************************
========================================================= */
jQuery(document).ready(function(){
	
	jQuery("#main-menu li.menu-parent").on('click', function() {
		if(!jQuery(this).hasClass('current-item')){
			jQuery("#main-menu li.menu-parent").each(function(){
				jQuery(this).removeClass('current-item');
				if(!jQuery(this).children('ul').is(':hidden')) {
					jQuery(this).children('ul').toggle(300);
				}
			});
			jQuery(this).addClass('current-item');
			jQuery(this).children('ul').toggle(300);
		} else {
			jQuery(this).children('ul').toggle(300);
			jQuery(this).removeClass('current-item');
		}
	});
	
	jQuery("#main-menu li").each(function() {
		if(jQuery(this).has("ul").length > 0) {
			jQuery(this).addClass("menu-arrow")
		}
	});

})
/* =========================================================
**********************Pretty Photo**************************
========================================================= */
 jQuery(document).ready(function(){
    jQuery("a[rel^='prettyPhoto']").prettyPhoto();
  });

/* =========================================================
***********************Effect when hover********************
========================================================= */
jQuery(document).ready(function(){
	jQuery(".hover-effect").mouseenter(function(){
        jQuery(this).fadeTo(400, 0.8);
    }).mouseleave(function(){
        jQuery(this).fadeTo(400, 1);
    });
});
/* =========================================================
********************Comment Form Validation*****************
========================================================= */
jQuery(document).ready(function(){
    if(jQuery("#comments-form").length > 0){
	// Validate the contact form
	  jQuery('#comments-form').validate({
	
		// Add requirements to each of the fields
		rules: {
			name: {
				required: true,
				minlength: 2
			},
			email: {
				required: true,
				email: true
			},
			message: {
				required: true,
				minlength: 10
			}
		},
		
		// Specify what error messages to display
		// when the user does something horrid
		messages: {
			name: {
				required: "Please enter your name.",
				minlength: jQuery.format("At least {0} characters required.")
			},
			email: {
				required: "Please enter your email.",
				email: "Please enter a valid email."
			},
			message: {
				required: "Please enter a message.",
				minlength: jQuery.format("At least {0} characters required.")
			}
		},
		
		// Use Ajax to send everything to processForm.php
		submitHandler: function(form) {
			jQuery("#submit-comment").attr("value", "Sending...");
			jQuery(form).ajaxSubmit({
				success: function(responseText, statusText, xhr, $form) {
					jQuery("#response").html(responseText).hide().slideDown("fast");
					jQuery("#submit-comment").attr("value", "Comment");
				}
			});
			return false;
		}
	  });
	}
});
/* =========================================================
*******************Fix height Felix-map*********************
========================================================= */
function fix_height(){
	var view_height = jQuery("#main-content").height();
	var contact_height = jQuery(".contact-box").height();
	var felix_map_height = jQuery(".felix-map").height();
	if (felix_map_height < view_height) {
		jQuery(".felix-map").height(view_height);
	}
	
	if (contact_height < view_height) {
		jQuery(".contact-box").height(view_height);
	}
	
}
jQuery(document).ready(function(){
    fix_height();  
});
jQuery(window).live('resize', function() {
	 fix_height(); 
});

/* =========================================================
***********Calculation width of #center-col*****************
========================================================= */
function fix_width(){
	if (jQuery(".flx-sidebar").length > 0 ) {	
		var main_content_width = jQuery("#main-content").width();
		var right_sidebar_width = jQuery(".flx-sidebar").width();
		var center_col_width = main_content_width - right_sidebar_width;
		jQuery("#center-col").width(center_col_width);
	}
}

jQuery(document).ready(function(){
    fix_width();  
});
jQuery(window).resize(function() {
	 fix_width();
});

function fix_width_2(){
	var view_device_width = jQuery(window).width();
	
	if (view_device_width < 1280 ) {
		main_content_width_2 = view_device_width - 290;		
	
	jQuery(".fixed-width #main-content").width(main_content_width_2);
	if (jQuery(".fixed-width .flx-sidebar").length > 0) {
		var right_sidebar_width_2 = jQuery(".fixed-width .flx-sidebar").width();
		var center_col_width_2 = main_content_width_2 - right_sidebar_width_2 - 50;
		
		jQuery(".fixed-width #center-col").width(center_col_width_2).css("margin-left",20);
		jQuery(".left-sidebar-page.fixed-width #center-col").width(center_col_width_2).css("margin-left",0);
		jQuery(".fixed-width .flx-sidebar").css("margin-left",10);
		jQuery(".fixed-width .flx-sidebar").css("margin-right",20);
		jQuery(".left-sidebar-page.fixed-width .flx-sidebar").css("margin-left",20);
		jQuery(".left-sidebar-page.fixed-width .flx-sidebar").css("margin-right",10);
	}
	}
	else if (view_device_width > 1281) {
		jQuery(".fixed-width #main-content").width(980);
		var center_col_width_2 = 980 - 260;
		jQuery(".fixed-width #center-col").width(center_col_width_2).css("margin-left",0);
		jQuery(".fixed-width .flx-sidebar").css("margin-left",0);
		jQuery(".fixed-width .flx-sidebar").css("margin-right",0);
		jQuery(".left-sidebar-page.fixed-width .flx-sidebar").css("margin-right",10);
	}
}

jQuery(document).ready(function(){
    fix_width_2();  
});
jQuery(window).resize(function() {
	 fix_width_2(); 
});

/* =========================================================
*****************Fix width for image in post****************
========================================================== */
/*function imgs_width(){
	var imgs = jQuery(".entry-thumb");
	if (imgs.length == 1){
		if ( imgs.width() > imgs.parent().width()) {
			imgs.addClass('auto-100');
		}
	}
}
jQuery(document).ready(function(){
    imgs_width();  
});
jQuery(window).live('resize', function() {
	 imgs_width(); 
});*/

 /* =========================================================
*****************************Tabs****************************
========================================================== */

jQuery(document).ready(function() {
//Default Action Product Tab
	jQuery(".tab-content").hide(); //Hide all content
	jQuery("ul.tabs li:first").addClass("active").show(); //Activate first tab
	jQuery(".tab-content:first").show(); //Show first tab content
	//On Click Event Product Tab
	jQuery("ul.tabs li").click(function() {
		jQuery("ul.tabs li").removeClass("active"); //Remove any "active" class
		jQuery(this).addClass("active"); //Add "active" class to selected tab
		jQuery(".tab-content").hide(); //Hide all tab content
		var activeTab = jQuery(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		jQuery(activeTab).fadeIn(); //Fade in the active content
		return false;
		
	});
	
	jQuery(".sidebar-tab-content").hide(); //Hide all content
	jQuery("ul.sidebar-tabs li:first").addClass("active").show(); //Activate first tab
	jQuery(".sidebar-tab-content:first").show(); //Show first tab content
	//On Click Event Product Tab
	jQuery("ul.sidebar-tabs li").click(function() {
		jQuery("ul.sidebar-tabs li").removeClass("active"); //Remove any "active" class
		jQuery(this).addClass("active"); //Add "active" class to selected tab
		jQuery(".sidebar-tab-content").hide(); //Hide all tab content
		var activeTab = jQuery(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		jQuery(activeTab).fadeIn(); //Fade in the active content
		return false;
		
	});
});

/* =========================================================
***********************Flickr Feed**************************
==========================================================*/
jQuery(document).ready(function(){ 
	jQuery('#flickr-feed-1').jflickrfeed({
		limit: 6,
		qstrings: {
			id: '92032055@N03'
		},
		itemTemplate:
			'<li class="flickr-badge-image">' +
			'<a rel="prettyPhoto[kopa-flickr]" href="{{image}}" title="{{title}}">' +
			'<img src="{{image_s}}" alt="{{title}}" width="65px" heigth="65px" />' +
			'</a>' +
			'</li>'
	}, function(data) {
			jQuery("a[rel^='prettyPhoto']").prettyPhoto({
			show_title: false,
			deeplinking:false
		}).mouseenter(function(){
			//jQuery(this).find('img').fadeTo(500, 0.6);
		}).mouseleave(function(){
			//jQuery(this).find('img').fadeTo(400, 1);
		});
	});
});
/* =========================================================
*************************Accordion**************************
========================================================= */
jQuery(document).ready(function() {
    (function() {
        var acc_wrapper=jQuery('.acc-wrapper');
        if (acc_wrapper.length >0) 
        {
            jQuery('.acc-wrapper .accordion-container').hide();
            jQuery.each(acc_wrapper, function(index, item){
                jQuery(this).find(jQuery('.accordion-title')).first().addClass('active').next().show();
				
            });
            jQuery('.accordion-title').on('click', function(e) {
                if( jQuery(this).next().is(':hidden') ) {
                    jQuery(this).parent().find(jQuery('.active')).removeClass('active').next().slideUp(300);
                    jQuery(this).toggleClass('active').next().slideDown(300);
                }
                e.preventDefault();
            });
        }
    })();
});

/* =========================================================
********************Testimonials****************************
========================================================= */		
jQuery(function() {
    jQuery('#flexslider').flexslider({
        animation: "slide",
        slideshow: true, 
        controlsContainer: ".flexslider-container"
    });
});

/* =========================================================
*********************Background slide***********************
========================================================= */
jQuery(document).ready(function() {
$.vegas('slideshow', {
	backgrounds:[
		{ src:'placeholders/01.jpg', fade:1000 },
		{ src:'placeholders/02.jpg', fade:1000 },
		{ src:'placeholders/03.jpg', fade:1000 }
	]
	})('overlay', {
		src:'placeholders/vegas/overlays/06.png'
});

})

/* =========================================================
*********************Backgorund video***********************
========================================================= */
$('document').ready(function() {
	var options = { videoId: 'UWF7dZTLW4c', start: 3 };
	$('.home-s4 #main-content').tubular(options);
	// f-UGhWj1xww cool sepia hd
	// 49SKbS7Xwf4 beautiful barn sepia
});

/* =========================================================
********************Isotope for magical layouts*************
========================================================= */
$.Isotope.prototype._getCenteredMasonryColumns = function() {
	this.width = this.element.width();
	
	var parentWidth = this.element.parent().width();
	
				  // i.e. options.masonry && options.masonry.columnWidth
	var colW = this.options.masonry && this.options.masonry.columnWidth ||
				  // or use the size of the first item
				  this.$filteredAtoms.outerWidth(true) ||
				  // if there's no items, use size of container
				  parentWidth;
	
	var cols = Math.floor( parentWidth / colW );
	cols = Math.max( cols, 1 );

	// i.e. this.masonry.cols = ....
	this.masonry.cols = cols;
	// i.e. this.masonry.columnWidth = ...
	this.masonry.columnWidth = colW;
  };
  
  $.Isotope.prototype._masonryReset = function() {
	// layout-specific props
	this.masonry = {};
	// FIXME shouldn't have to call this again
	this._getCenteredMasonryColumns();
	var i = this.masonry.cols;
	this.masonry.colYs = [];
	while (i--) {
	  this.masonry.colYs.push( 0 );
	}
  };

  $.Isotope.prototype._masonryResizeChanged = function() {
	var prevColCount = this.masonry.cols;
	// get updated colCount
	this._getCenteredMasonryColumns();
	return ( this.masonry.cols !== prevColCount );
  };
  
  $.Isotope.prototype._masonryGetContainerSize = function() {
	var unusedCols = 0,
		i = this.masonry.cols;
	// count unused columns
	while ( --i ) {
	  if ( this.masonry.colYs[i] !== 0 ) {
		break;
	  }
	  unusedCols++;
	}
	
	return {
		  height : Math.max.apply( Math, this.masonry.colYs ),
		  // fit container to columns that have been used;
		  width : (this.masonry.cols - unusedCols) * this.masonry.columnWidth
		};
  };

jQuery(window).load(function(){

  var $container = $('#container');
  
  // add randomish size classes
  $container.find('.element').each(function(){
	var $this = $(this),
		number = parseInt( $this.find('.number').text(), 10 );
	if ( number % 7 % 2 === 1 ) {
	  $this.addClass('width2');
	}
	if ( number % 3 === 0 ) {
	  $this.addClass('height2');
	}
  });

  $container.isotope({
	masonry: {
	  columnWidth: 100
	},
	sortBy: 'number',
	getSortData: {
	  number: function( $elem ) {
		var number = $elem.hasClass('element') ? 
		  $elem.find('.number').text() :
		  $elem.attr('data-number');
		return parseInt( number, 10 );
	  },
	  alphabetical: function( $elem ) {
		var name = $elem.find('.name'),
			itemText = name.length ? name : $elem;
		return itemText.text();
	  }
	}
  });

  
  var $optionSets = $('#options .option-set'),
	  $optionLinks = $optionSets.find('a');

  $optionLinks.click(function(){
	var $this = $(this);
	// don't proceed if already selected
	if ( $this.hasClass('selected') ) {
	  return false;
	}
	var $optionSet = $this.parents('.option-set');
	$optionSet.find('.selected').removeClass('selected');
	$this.addClass('selected');

	// make option object dynamically, i.e. { filter: '.my-filter-class' }
	var options = {},
		key = $optionSet.attr('data-option-key'),
		value = $this.attr('data-option-value');
	// parse 'false' as false boolean
	value = value === 'false' ? false : value;
	options[ key ] = value;
	if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
	  // changes in layout modes need extra logic
	  changeLayoutMode( $this, options )
	} else {
	  // otherwise, apply new options
	  $container.isotope( options );
	}
	
	return false;
  });

});
/* =========================================================
**************************Load more*************************
========================================================= */
jQuery(function(){

  var $container = jQuery('#container');

  $container.isotope({
	itemSelector : '.element'
  });
  
  $container.infinitescroll({
	navSelector  : '#page_nav',    // selector for the paged navigation 
	nextSelector : '#page_nav a',  // selector for the NEXT link (to page 2)
	itemSelector : '.element',     // selector for all items you'll retrieve
	loading: {
		finishedMsg: 'No more items to load.',
		img: 'http://i.imgur.com/qkKy8.gif'
	  }
	},
	// call Isotope as a callback
	function( newElements ) {
	  $container.isotope( 'appended', $( newElements ) );
	  $("a[rel^='prettyPhoto']").prettyPhoto();  
	}
  );
});

/* =========================================================
Filter by category picker
============================================================ */
jQuery(document).ready(function(){
	jQuery(".filter-picker").click(function() {
		jQuery("#filter-by-category").slideToggle(300);
	});

})

/* =========================================================
**************************Time Line*************************
========================================================= */
$(function() {

	var $sidescroll	= (function() {
			
			// the row elements
		var $rows			= $('#ss-container > div.ss-row'),
			// we will cache the inviewport rows and the outside viewport rows
			$rowsViewport, $rowsOutViewport,
			// navigation menu links
			$links			= $('#ss-links a'),
			// the window element
			$win			= $(window),
			// we will store the window sizes here
			winSize			= {},
			// used in the scroll setTimeout function
			anim			= false,
			// page scroll speed
			scollPageSpeed	= 2000 ,
			// page scroll easing
			scollPageEasing = 'easeInOutExpo',
			// perspective?
			hasPerspective	= false,
			
			perspective		= hasPerspective && Modernizr.csstransforms3d,
			// initialize function
			init			= function() {
				
				// get window sizes
				getWinSize();
				// initialize events
				initEvents();
				// define the inviewport selector
				defineViewport();
				// gets the elements that match the previous selector
				setViewportRows();
				// if perspective add css
				if( perspective ) {
					$rows.css({
						'-webkit-perspective'			: 600,
						'-webkit-perspective-origin'	: '50% 0%'
					});
				}
				// show the pointers for the inviewport rows
				$rowsViewport.find('.ss-circle').addClass('ss-circle-deco');
				// set positions for each row
				placeRows();
				
			},
			// defines a selector that gathers the row elems that are initially visible.
			// the element is visible if its top is less than the window's height.
			// these elements will not be affected when scrolling the page.
			defineViewport	= function() {
			
				$.extend( $.expr[':'], {
				
					inviewport	: function ( el ) {
						if ( $(el).offset().top < winSize.height ) {
							return true;
						}
						return false;
					}
				
				});
			
			},
			// checks which rows are initially visible 
			setViewportRows	= function() {
				
				$rowsViewport 		= $rows.filter(':inviewport');
				$rowsOutViewport	= $rows.not( $rowsViewport )
				
			},
			// get window sizes
			getWinSize		= function() {
			
				winSize.width	= $win.width();
				winSize.height	= $win.height();
			
			},
			// initialize some events
			initEvents		= function() {
				
				// navigation menu links.
				// scroll to the respective section.
				$links.on( 'click.Scrolling', function( event ) {
					
					// scroll to the element that has id = menu's href
					$('html, body').stop().animate({
						scrollTop: $( $(this).attr('href') ).offset().top
					}, scollPageSpeed, scollPageEasing );
					
					if($('#dd').length > 0) {
						var opt = $(this);
						$('#dd').children('span').text($('#dd').children('span').text().substr(0, 4) + ': ' + opt.text());
						$('#dd').removeClass('active');
					}
					
					
					return false;
				
				});
				
				$(window).on({
					// on window resize we need to redefine which rows are initially visible (this ones we will not animate).
					'resize.Scrolling' : function( event ) {
						
						// get the window sizes again
						getWinSize();
						// redefine which rows are initially visible (:inviewport)
						setViewportRows();
						// remove pointers for every row
						$rows.find('.ss-circle').removeClass('ss-circle-deco');
						// show inviewport rows and respective pointers
						$rowsViewport.each( function() {
						
							$(this).find('div.ss-left')
								   .css({ left   : '0%' })
								   .end()
								   .find('div.ss-right')
								   .css({ right  : '0%' })
								   .end()
								   .find('.ss-circle')
								   .addClass('ss-circle-deco');
						
						});
					
					},
					// when scrolling the page change the position of each row	
					'scroll.Scrolling' : function( event ) {
						
						// set a timeout to avoid that the 
						// placeRows function gets called on every scroll trigger
						if( anim ) return false;
						anim = true;
						setTimeout( function() {
							
							placeRows();
							anim = false;
							
						}, 10 );
					
					}
				});
			
			},
			// sets the position of the rows (left and right row elements).
			// Both of these elements will start with -50% for the left/right (not visible)
			// and this value should be 0% (final position) when the element is on the
			// center of the window.
			placeRows		= function() {
				
					// how much we scrolled so far
				var winscroll	= $win.scrollTop(),
					// the y value for the center of the screen
					winCenter	= winSize.height / 2 + winscroll;
				
				// for every row that is not inviewport
				$rowsOutViewport.each( function(i) {
					
					var $row	= $(this),
						// the left side element
						$rowL	= $row.find('div.ss-left'),
						// the right side element
						$rowR	= $row.find('div.ss-right'),
						// top value
						rowT	= $row.offset().top;
					
					// hide the row if it is under the viewport
					if( rowT > winSize.height + winscroll ) {
						
						if( perspective ) {
						
							$rowL.css({
								'-webkit-transform'	: 'translate3d(-75%, 0, 0) rotateY(-90deg) translate3d(-75%, 0, 0)',
								'opacity'			: 0
							});
							$rowR.css({
								'-webkit-transform'	: 'translate3d(75%, 0, 0) rotateY(90deg) translate3d(75%, 0, 0)',
								'opacity'			: 0
							});
						
						}
						else {
						
							$rowL.css({ left 		: '-50%' });
							$rowR.css({ right 		: '-50%' });
						
						}
						
					}
					// if not, the row should become visible (0% of left/right) as it gets closer to the center of the screen.
					else {
							
							// row's height
						var rowH	= $row.height(),
							// the value on each scrolling step will be proporcional to the distance from the center of the screen to its height
							factor 	= ( ( ( rowT + rowH / 2 ) - winCenter ) / ( winSize.height / 2 + rowH / 2 ) ),
							// value for the left / right of each side of the row.
							// 0% is the limit
							val		= Math.max( factor * 50, 0 );
							
						if( val <= 0 ) {
						
							// when 0% is reached show the pointer for that row
							if( !$row.data('pointer') ) {
							
								$row.data( 'pointer', true );
								$row.find('.ss-circle').addClass('ss-circle-deco');
							
							}
						
						}
						else {
							
							// the pointer should not be shown
							if( $row.data('pointer') ) {
								
								$row.data( 'pointer', false );
								$row.find('.ss-circle').removeClass('ss-circle-deco');
							
							}
							
						}
						
						// set calculated values
						if( perspective ) {
							
							var	t		= Math.max( factor * 75, 0 ),
								r		= Math.max( factor * 90, 0 ),
								o		= Math.min( Math.abs( factor - 1 ), 1 );
							
							$rowL.css({
								'-webkit-transform'	: 'translate3d(-' + t + '%, 0, 0) rotateY(-' + r + 'deg) translate3d(-' + t + '%, 0, 0)',
								'opacity'			: o
							});
							$rowR.css({
								'-webkit-transform'	: 'translate3d(' + t + '%, 0, 0) rotateY(' + r + 'deg) translate3d(' + t + '%, 0, 0)',
								'opacity'			: o
							});
						
						}
						else {
							
							$rowL.css({ left 	: - val + '%' });
							$rowR.css({ right 	: - val + '%' });
							
						}
						
					}	
				
				});
			
			};
		
		return { init : init };
	
	})();
	
	$sidescroll.init();
	
});
/* =========================================================
*********************CSS for Select box*********************
========================================================= */
$(document).ready(function(){
	$('.flx-select').customSelect();
});
/* =========================================================
*************************Mobile Filter**********************
========================================================= */
$(function() {

    var $container = $('#container'),
        $select = $('#filters select');

    $select.change(function() {
        var filters = $(this).val();
;
        $container.isotope({
            filter: filters
        });
    });

});
/* for Blog Timeline*/
function DropDown(el) {
	this.dd = el;
	this.placeholder = this.dd.children('span');
	this.opts = this.dd.find('ul.dropdown > li');
	this.val = '';
	this.index = -1;
	this.initEvents();
}
DropDown.prototype = {
	initEvents : function() {
		var obj = this;

		obj.dd.on('click', function(event){
			$(this).toggleClass('active');
			return false;
		});

		obj.opts.on('click',function(event){
			var opt = $(this);
			obj.val = opt.text();
			obj.index = opt.index();
			obj.placeholder.text(obj.placeholder.text() + ': ' + obj.val);
			return false;
		});
	},
	getValue : function() {
		return this.val;
	},
	getIndex : function() {
		return this.index;
	}
}

$(function() {

	var dd = new DropDown( $('#dd') );

	$(document).click(function() {
		// all dropdowns
		$('.wrapper-dropdown-1').removeClass('active');
	});

});

/* =========================================================
*************************Stiky navigation*******************
========================================================= */
$(function() {
	if($('#sticky_navigation').length > 0) {
	// grab the initial top offset of the navigation 
	var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;
	
	// our function that decides weather the navigation bar should have "fixed" css position or not.
	var sticky_navigation = function(){
		var scroll_top = $(window).scrollTop(); // our current vertical position from the top
		
		// if we've scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
		if (scroll_top > sticky_navigation_offset_top) { 
			$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
		} else {
			$('#sticky_navigation').css({ 'position': 'relative' }); 
		}   
	};
	
	// run our function on load
	sticky_navigation();
	
	// and run it again every time you scroll
	$(window).scroll(function() {
		 sticky_navigation();
	});
	}
	// NOT required:
	// for this demo disable all links that point to "#"
	$('a[href="#"]').click(function(event){ 
		event.preventDefault(); 
	});
	
});
